/**
 * 
 */
package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Enumeration;
import java.util.Hashtable;

import logger.Logger;
import dbmanager.Column;
import dbmanager.DBManager;

/**
 * @author divyesh
 *
 */
public class DatabaseOperation 
{
	private Connection con;
	private Statement stmt;
	//private ResultSet rs;
	
	public Logger pLog;
	
	private String table = "property_details";
	private Hashtable<Object, Object> oldHash;
	private Hashtable<Object, Object> newHash;
	private String query = null;
	private String newHashString = "";
	private String oldHashString = "";
	private String insertFields = "";
	private String insertValues = "";
	private String deleteCondition = "";

	DBManager database;
	   
    /**
     * setTableName() method will set the Table Name on which we want to give query.
     * */
    public void setTableName(String tableName) 
    {
    	this.table = tableName;	
		
	}
    

    /**
     * setInsertHash() method will sets the condition for the table query part.
     * */
    public void setInsertHash(Hashtable<Object, Object> condition)
	{
		this.newHash = new Hashtable<Object, Object>();
		this.newHash.putAll(condition);
		insertHashQuery(); // Calls the method for converting into the String.
	}
    
    /**
     * setConditionHash() method will sets the condition for the table query part.
     * */
    public void setOldCondition(Hashtable<Object, Object> condition)
	{
		this.oldHash = new Hashtable<Object, Object>();
		this.oldHash.putAll(condition);
		oldHashQuery(); // Calls the method for converting into the String.
	}
    
    /**
     * setTableHash() method will sets the table hash for the table query part.
     * */
    public void setNewCondition(Hashtable<Object, Object> condition)
	{
		this.newHash = new Hashtable<Object, Object>();
		this.newHash.putAll(condition);
		newHashQuery(); // Calls the method for converting into the String.
	}
    
    public void setDeleteHash(Hashtable<Object, Object> deleteHash) 
    {
    	this.oldHash = new Hashtable<Object, Object>();
    	this.oldHash = deleteHash; 
    	deleteHashQuery(); // Calls the method for converting into the String.
	}
    
    public void setDatabase(DBManager database)
    {
    	this.database = database;
    }
    
    /**
     * 
     * */
    public synchronized int getInsert()
    {
  	  int i=0;
  	  try
  	  { 		  
  		  query = "INSERT INTO " + table;
  		  
  		  try 
  		  {
			if(insertFields.length() != 0)
				  query = query + "(" + insertFields + ")";
		  } 
  		  catch (Exception e)  { }
  		  
  		  try 
  		  {
			if(insertValues.length() != 0)
				  query = query + " VALUES (" + insertValues + ")";
		  } 
  		  catch (Exception e) { }
  		  
  		  System.out.println("The query is : " + query);
  		  stmt = con.createStatement();
  		  int j = stmt.executeUpdate(query.toString());
  		  System.out.println(j);
  		  if(j>0)
  		  {
  			 System.out.println("Data inserted successfully");
  			 i=1;
  		  }
  	  }
  	  catch(Exception e)
  	  {
  		  e.printStackTrace();
  	  }
  	  return i;
    }
	
    /**
     * 
     * */
    public synchronized int getUpdate()
    {
  	  	int i = 0;
  	  	try
  	  	{
  	  		  query = "UPDATE " + table;
  	  		  
  	  		  try 
  	  		  {
				if(newHashString.length() != 0)
					  query = query + " SET " + newHashString;
			  } 
  	  		  catch (Exception e)  { }
  	  		  
  	  		  try 
  	  		  {
				if(oldHashString.length() != 0)
					  query = query + " WHERE " + oldHashString;
			  } 
  	  		  catch (Exception e) { }
  	  		  
	  		  System.out.println("The query is :"+query);
	  		  stmt=con.createStatement();
	  		  int j=stmt.executeUpdate(query.toString());
	  		  if(j>0)
	  		  {
	  			  i=1;
	  		  }
  	  }
  	  catch(Exception e)
  	  {
  		  e.printStackTrace();
  	  }
  	  return i;
    }
    
    public synchronized int getDelete()
    {
    	int i=0;
    	try
    	{    		
			query = "DELETE FROM " + table;
			
			try 
	  		{
				if(deleteCondition.length() != 0)
					query = query + " WHERE " + deleteCondition;
	  		} 
	  		catch (Exception e) { }
    		        		
    		System.out.println("The query is : " + query);
    		stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
    		int j=stmt.executeUpdate(query);
    		if(j>0)
    		{
    			i=1;
    		}
    	}
	  	catch(Exception e)
	  	{
	  		  e.printStackTrace();
	  	}
	  	return i;
	 
    }

    /**
     * insertHashQuery() - It will creats the string from the Hash Table. Which get stores into the respected string variable.  
     * */
    
    private void insertHashQuery() 
    {
    	if(table.length() != 0)
    	{
    		Enumeration keys = newHash.keys();
    		while(keys.hasMoreElements())
    		{
    			String key = keys.nextElement().toString();
    			String value = newHash.get(key).toString();
    			insertFields = insertFields + key + ", ";
    			insertValues = insertValues + " '"+ value + "', ";
    		}
    		insertFields = insertFields.substring(0, insertFields .length() - 2);
    		insertValues = insertValues.substring(0, insertValues .length() - 2);
    	}
    	else
    	{
    		System.out.println(" Table Name Does Not Exists. ");
    	}
	}
    
  

    /**
     * oldHashQuery() - It will creats the string from the Hash Table. Which get stores into the respected string variable.  
     * */
    private void oldHashQuery()
    {
    	if(table.length() != 0)
		{
	    	if(oldHash.isEmpty())
			{
				System.out.println(" Table Value Is Not Present ");
				query = "SELECT * FROM " + table;
			}
			else
			{
				Enumeration<Object> hashKeys;
				hashKeys = oldHash.keys();
				
				while(hashKeys.hasMoreElements())
				{
					String columnmName = hashKeys.nextElement().toString();
					String columnValue = oldHash.get(columnmName).toString();
					oldHashString = oldHashString  + columnmName + " = " + columnValue + " AND "; 
				}
				oldHashString  = oldHashString .substring(0, oldHashString .length() - 4);
				//query = "SELECT mid, pid, pv, vt, ref, fd, td FROM " + table + " where " + tableHashQuery;
			}
		}
    	else
		{
			System.out.println(" Table Name Does Not Exists. ");
		}	
    }
    
  
    /**
     * newHashQuery() - It will creats the string from the Hash Table. Which get stores into the respected string variable.  
     * */
    private void newHashQuery() 
    {
    	if(table.length() != 0)
		{
	    	if(newHash.isEmpty())
			{
				System.out.println(" Condition Value Is Not Present ");
				query = "SELECT * FROM " + table;
			}
			else
			{
				Enumeration<Object> hashKeys;
				hashKeys = newHash.keys();
				
				while(hashKeys.hasMoreElements())
				{
					String columnmName = hashKeys.nextElement().toString();
					String columnValue = newHash.get(columnmName).toString();
					newHashString = newHashString + columnmName + " = " + columnValue + ", "; 
				}
				newHashString = newHashString.substring(0, newHashString.length() - 2);
				//query = "SELECT mid, pid, pv, vt, ref, fd, td FROM " + table + " where " + conditionHashQuery;
			}
		}
    	else
		{
			System.out.println(" Table Name Does Not Exists. ");
		}	
	}
    
    
    private void deleteHashQuery() 
    {
    	if(table.length() != 0)
    	{
    		if(oldHash.isEmpty())
    		{
    			System.out.println(" Condition Value Is Not Present ");
				//query = "DELETE FROM " + table;
    		}
    		else
    		{
    			Enumeration keys = oldHash.keys();
        		while(keys.hasMoreElements())
        		{
        			String key = keys.nextElement().toString();
      			  	String value = oldHash.get(key).toString();
      			  	
      			    deleteCondition = deleteCondition + key + " = '" + value + "' AND "; 
        			/*sbr.append(" "+key);
        			sbr.append("= '");
        			sbr.append(value+"' ");
        			sbr.append("AND");*/
        		}
        		deleteCondition = deleteCondition.substring(0, deleteCondition.length() - 4);
    		}
    		
    	}
    	else
		{
			System.out.println(" Table Name Does Not Exists. ");
		}	
	}
    /**
     * closeConnection() - It will close the connection.
     * */
    public synchronized void closeConnection()
    {
  	  try
  	  {
  		  if(con.isClosed()==false)
  		  {
  			  con.close(); 	
  		  }
  	  }
  	  catch(Exception e)
  	 {
  	 	e.printStackTrace();
  	 }
    }
    
    
     
	/**
	 * @param args
	 */
	public static void main(String[] args) 
	{
		DatabaseOperation dop = new DatabaseOperation();
		//dop.getConnect();
		
		Hashtable<Object, Object> old = new Hashtable<Object, Object>();
		old.put("mid", "121");
		old.put("pid", 1);
		dop.setDeleteHash(old);
		
		/*
		Hashtable<Object, Object> newHash = new Hashtable<Object, Object>();
		newHash.put("mid", "11");
		newHash.put("pid", "121");
		dop.setNewCondition(newHash);*/
		
		dop.getDelete();
	}

}
